package org.gunncs.actors;


import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import org.gunncs.actoriface.Actor;
import org.gunncs.actoriface.Robot;
import org.gunncs.actoriface.Sensor;

/**
 * <<Class summary>>
 *
 * @author Anand Gupta &lt;&gt;
 * @version $Rev$
 */
public class SnitchActor implements Actor {

    String message;
    DatagramConnection dgConnection;
    Datagram dg;

    public SnitchActor() {
        message = "";
        try {
            // The Connection is a broadcast so we specify it in the creation string
            dgConnection = (DatagramConnection) Connector.open("radiogram://broadcast:38");
            // Then, we ask for a datagram with the maximum size allowed
            dg = dgConnection.newDatagram(dgConnection.getMaximumLength());
        } catch (IOException ex) {
            System.out.println("Could not open radiogram broadcast connection");
            ex.printStackTrace();

        }
    }

    public void act(Robot r) {
        //Send Message
       // System.out.println("SNITCH:\n" + message);
       
        //int wall = r.getCreate();
        //System.out.println("Wall" +wall); 
        try {
            // We send the message (UTF encoded)
            dg.reset();
            dg.writeUTF(message);
            //dg.writeUTF(wall +" X " +"2");
            dgConnection.send(dg);
        //System.out.println("Broadcast is going through");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void updateSensors(Sensor[] sensors) {
        message = "";
        for (int i = 0; i < sensors.length; i++) {
            message += sensors[i].getID() + " ";
            for (int j = 0; j < sensors[i].getState().length-1; j++) {
                message += sensors[i].getState()[j];
                message+=";";
            }
            message+="1.0";
            if(i<sensors.length-1)
                message += "\n";
        }
    }
}
